﻿from django.shortcuts import render
from django.http import HttpResponse, FileResponse
from django.db.utils import IntegrityError

from . import functions
from pathlib import Path
from django.views.decorators.csrf import csrf_exempt
from django.conf import settings
from django.shortcuts import redirect
from openpyxl import load_workbook
import time


BASE_DIR = settings.BASE_DIR


def hello(request, num=10):
    return HttpResponse(functions.get_vocabulary(num))


def upload_page(request):
    return render(request, 'upload.html', None)


@csrf_exempt
def upload(request):
    file = request.FILES.get('upload_file', None)
    if not file:
        return HttpResponse("no file!")
    filename = str(int(time.time()*10)) + str(file.name)
    dir = Path(BASE_DIR).joinpath('uploads')
    if not Path.exists(dir):
        dir.mkdir()
    path = dir.joinpath(filename)
    dest = open(path, 'wb')
    for chunk in file.chunks():
        dest.write(chunk)
    dest.close()
    response = redirect('/foruse/showresult')
    response.set_cookie('filename', filename)
    return response  # request.COOKIES['键名']


def show_result(request):
    file = request.COOKIES['filename']
    file = str(Path(BASE_DIR)/'uploads'/str(file))
    functions.do_exl_change(file)
    wb = load_workbook(file)
    ls = []
    content = {'is_error': '以下单词中也许存在拼写错误', 'ls': ls}
    sheet = wb['Sheet1']
    for i in range(1, sheet.max_row + 1):
        temp_mean = sheet['B' + str(i)].value
        if temp_mean is None or temp_mean == '':
            ls.append({'tango': sheet['A' + str(i)].value,
                       'mean': temp_mean})
    if len(ls) > 0:
        content['show_btn'] = None
        return render(request, 'tango_content.html', content)
    for i in range(1, 10):
        ls.append({'tango': sheet['A' + str(i)].value,
                   'mean': sheet['B' + str(i)].value})
    content['is_error'] = '未发现错误，以下是部分展示'
    content['show_btn'] = 1
    return render(request, 'tango_content.html', content)


def confirm(request):
    file = str(Path(BASE_DIR) / 'uploads' / str(request.COOKIES['filename']))
    try:
        functions.read_exl_insert(file)
    except IntegrityError:
        return render(request, 'finish.html', {'result': '完成！'})
    return render(request, 'finish.html', {'result': '完成！'})


def delete(request):
    from .models import Tango
    # Tango.delete_everything()
    Tango.objects.all().delete()
    return HttpResponse('''<a href="/foruse/uploadpage">返回主页</a>''')
# TRUNCATE mainapp_tango


def show_file_list(request):
    return render(request, 'filelist.html', {'ls': functions.get_file_list()})


def download(request, file_name):
    f = open(BASE_DIR / 'uploads' / file_name, 'rb')
    response = FileResponse(f)
    response['Content-Type'] = 'application/octet-stream'
    response['Content-Disposition'] = 'attachment;filename="%s"' % file_name
    return response


# def testdown(response):
#     file_name = '360base.dll'
#     f = open(BASE_DIR / 'uploads' / file_name, 'rb')
#     response = FileResponse(f)
#     response['Content-Type'] = 'application/octet-stream'
#     response['Content-Disposition'] = 'attachment;filename="%s"' % file_name
#     return response


